/*
 * @Author: zhangyang
 * @Date: 2022-06-20 12:00:09
 * @LastEditTime: 2022-06-23 17:29:30
 * @Description:
 */
import type { Obj } from 'api/typings/app/init';

enum OperateCode {
  success = 201,
  fail = 400,
  token_no_use = 401,
}

type Res = {
  code: OperateCode;
  data: any;
  msg: string;
};

const defaultSuccess: Res = {
  code: 201,
  data: {},
  msg: '操作成功！',
};

const defaultFail: Res = {
  code: 400,
  data: {},
  msg: '操作失败！',
};

export default {
  success(res: Partial<Res> = defaultSuccess) {
    return { ...defaultSuccess, ...res };
  },
  fail(res: Partial<Res> = defaultFail) {
    return { ...defaultFail, ...res };
  },
  generateToken(options: Obj, exp = 30 * 60) {
    // @ts-expect-error
    const token: string = this.app.jwt.sign(
      options,
      // @ts-expect-error
      this.app.config.jwt.secret,
      {
        expiresIn: `${exp}s`,
      },
    );

    return {
      expires: new Date(Date.now() + exp * 1000),
      token,
    };
  },
};
